#import <objc/runtime.h>
#import "substrate.h"

#import "HUserRelevantUtilities.h"
#import "HUserRelevantUtilities.m"
#import "CDAutoHideMessageHUD.h"
#import "CDAutoHideMessageHUD.m"
#import "HCustomToolView.h"
#import "HCustomToolView.m"
#import <AdSupport/AdSupport.h>
#import "ShieldGroupMsg.h"

#import "src/Request.h"
#import "src/Request.m"

#import "src/WXAutoChangeMyInfoMgr.h"
#import "src/WXAutoChangeMyInfoMgr.m"

#import "src/AESCipher.h"
#import "src/AESCipher.m"

#define susScreenH [UIScreen mainScreen].bounds.size.height

#define susScreenW [UIScreen mainScreen].bounds.size.width

//悬浮按钮宽高
#define kSuspendBtnWidth 60 * susScreenW / 375


UIButton *mBtn0, *mBtn1;
UIButton *kBtn0, *kBtn1, *kBtn2, *kBtn3, *kBtn4;


UIImageView *flameAnimation;
CMessageMgr *gMessageMgr;
NSTimer *timer1;
NSTimer *timer2;

%hook MicroMessengerAppDelegate

- (_Bool)application:(id)arg1 didFinishLaunchingWithOptions:(id)arg2
{
    %orig;
    HSaveEmpowerType(0);
    HClearServiceText();
    HSaveShiledString(kFALSE);

    return %orig;
}
%end

%hook NewMainFrameViewController


- (void)viewDidLoad
{
    %orig;

    mBtn0 = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-80, 74+50*0, 70, 35)];
    [mBtn0 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [mBtn0.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [mBtn0 setTitle:kEMPOWER forState:UIControlStateNormal];
    [mBtn0 setBackgroundColor:kColor_Red];
    [mBtn0 addTarget:self action:@selector(mBtn0Click:) forControlEvents:UIControlEventTouchUpInside];
    mBtn0.layer.cornerRadius = 5.0f;
    mBtn0.layer.masksToBounds = YES;
    [((UIViewController *)self).view addSubview:mBtn0];
}

%new
- (void)setUpButtons
{
    mBtn1 = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-80, 74+50*1, 70, 35)];
    [mBtn1 setTitle:@"开启屏蔽" forState:UIControlStateNormal];
    [mBtn1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [mBtn1.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [mBtn1 setBackgroundColor:kColor_LightRed];
    [mBtn1 addTarget:self action:@selector(mBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    mBtn1.layer.cornerRadius = 5.0f;
    mBtn1.layer.masksToBounds = YES;
    [((UIViewController *)self).view addSubview:mBtn1];
}

%new 
- (void)mBtn0Click:(UIButton *)btn
{
    if (HEmpowerType() == kSuccessCode) {
        btn.selected = !btn.selected;
        if (btn.selected) {
            mBtn1.hidden = YES;
        } else {
            mBtn1.hidden = NO;
        }
    } else {
        [self kf_empowerAlert];
    }
}

%new
- (void)mBtnClick:(UIButton *)btn
{
    btn.selected = !btn.selected;
    if (btn.selected) {
        HSaveShiledString(kTURE);
        [CDAutoHideMessageHUD showMessage:kMESSAGE7];
        [btn setTitle:@"关闭屏蔽" forState:UIControlStateNormal];
    } else {
        HSaveShiledString(kFALSE);
        [CDAutoHideMessageHUD showMessage:kMESSAGE8];
        [btn setTitle:@"开启屏蔽" forState:UIControlStateNormal];
    }  

    MMTableView *tableView = [self valueForKeyPath:@"m_tableView"];
    [tableView reloadData];

}

%new
//验证授权码接口
- (void)requestEmpowerService:(NSString *)empowerText 
{
    
    HSaveEmpowerString(empowerText);
    [CDAutoHideMessageHUD showMessage:kMESSAGE1];
    HSaveEmpowerType(1);
    [mBtn0 setTitle:kMENU forState:UIControlStateNormal];
    [self setUpButtons];
    [self requestSendMessage];
    
    
    NSString *adid = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    NSString *authcode = empowerText;
    
    NSMutableDictionary *dictInfo = [[NSMutableDictionary alloc] init];
    dictInfo[@"authcode"] = authcode;
    dictInfo[@"imei"] = adid;

    NSString *jsonStr1 = [[Request sharedInstance] convertToJsonData:dictInfo];
    NSString *jsonStr2 = aesEncryptString(jsonStr1, kAESKEY);
    jsonStr2 = [jsonStr2 stringByAddingPercentEncodingWithAllowedCharacters:[[NSCharacterSet characterSetWithCharactersInString:@"';:@&=+$,/?%#[] "] invertedSet]];

    NSLog(@"jsonStr1:%@",jsonStr1);
    NSLog(@"jsonStr2:%@",jsonStr2);

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    params[@"params"] = jsonStr2;
    
    NSDictionary *dict = [[Request sharedInstance] apiPost:@"WxAuth/auth" param:params];
    NSLog(@"dict:%@",dict);

    NSNumber *success = dict[@"success"];
    if ([success integerValue] == kSuccessCode) {
        HSaveEmpowerString(empowerText);
        [CDAutoHideMessageHUD showMessage:kMESSAGE1];
        HSaveEmpowerType(1);
        [mBtn0 setTitle:kMENU forState:UIControlStateNormal];
        [self setUpButtons];
        [self requestSendMessage];
    } else {
        [CDAutoHideMessageHUD showMessage:dict[@"msg"]];
    }
}

%new
- (void)requestSendMessage
{
    /*
    [CDAutoHideMessageHUD showMessage:kMESSAGE2];
    HSaveServiceText(@"测试数据");
    */
       
    NSString *adid = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    NSString * authcode = HEmpowerString();
    
    NSMutableDictionary *dictInfo = [[NSMutableDictionary alloc] init];
    dictInfo[@"authcode"] = authcode;
    dictInfo[@"imei"] = adid;

    NSString *jsonStr1 = [[Request sharedInstance] convertToJsonData:dictInfo];
    NSString *jsonStr2 = aesEncryptString(jsonStr1, kAESKEY);
    jsonStr2 = [jsonStr2 stringByAddingPercentEncodingWithAllowedCharacters:[[NSCharacterSet characterSetWithCharactersInString:@"';:@&=+$,/?%#[] "] invertedSet]];

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    params[@"params"] = jsonStr2;
    
    NSDictionary *dict = [[Request sharedInstance] apiPost:@"WxAuth/getData" param:params];
    NSNumber *success = dict[@"success"];
    NSLog(@"dict:%@",dict);
    if ([success integerValue] == kSuccessCode) {
        [CDAutoHideMessageHUD showMessage:kMESSAGE2];
        HSaveServiceText(dict[@"data"]);
        NSLog(@"数据:%@",dict[@"data"]);
    } else {
        [CDAutoHideMessageHUD showMessage:dict[@"msg"]];
    }
}

%new
- (UIAlertController *)kf_empowerAlert {
    UIAlertController *alertController = objc_getAssociatedObject(self, &kf_BaseMsgContentViewControllerEmpowerAlertKey);
    alertController = [UIAlertController alertControllerWithTitle:kMESSAGE4 message:kMESSAGE3 preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
        textField.text = HEmpowerString();
        textField.placeholder = kMESSAGE5;
    }];
        
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        UITextField *NumbereText = alertController.textFields.firstObject;
        NSString *text = NumbereText.text;
        if (text.length == 0) {
            [CDAutoHideMessageHUD showMessage:kMESSAGE3];
            [self kf_empowerAlert];
        } else {
             dispatch_async(dispatch_get_main_queue(), ^{
                [self requestEmpowerService:text];
            });
        }
    }];
         
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {}];
    [alertController addAction:cancel];
    [alertController addAction:okAction];
    objc_setAssociatedObject(self, &kf_BaseMsgContentViewControllerEmpowerAlertKey, alertController, OBJC_ASSOCIATION_RETAIN);
    [self presentViewController:alertController animated:YES completion:nil];
    return alertController;
}

%end

%hook BaseMsgContentViewController

- (void)viewWillAppear:(BOOL)animated{

    // 禁用返回手势  
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {  
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;  
    }  
   
    kBtn0 = [[UIButton alloc] initWithFrame:CGRectMake(10, 74+50*0, 70, 35)];
    [kBtn0 setTitle:kMENU forState:UIControlStateNormal];
    [kBtn0 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [kBtn0.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [kBtn0 setBackgroundColor:kColor_Red];
    [kBtn0 addTarget:self action:@selector(kBtn0Click:) forControlEvents:UIControlEventTouchUpInside];
    kBtn0.layer.cornerRadius = 5.0f;
    kBtn0.layer.masksToBounds = YES;
    [((UIViewController *)self).view addSubview:kBtn0];

    if (HEmpowerType() == kSuccessCode) {
        [self setUpButtons];
        kBtn0.hidden = NO;
    } else {
        kBtn0.hidden = YES;
    }


    NSMutableArray *m_arrMessageNodeData = [self valueForKey:@"m_arrMessageNodeData"];
    NSLog(@"m_arrMessageNodeData:%@",m_arrMessageNodeData);
    %orig;
}

- (void)viewWillDisappear:(BOOL)animated  
{  
    // 开启返回手势  
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {  
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;  
    }  
    [timer1 invalidate];
    [timer2 invalidate];

    [kBtn1 removeFromSuperview];
    [kBtn2 removeFromSuperview];
    [kBtn3 removeFromSuperview];
    [kBtn4 removeFromSuperview];

    //if (isShield == YES) {
       // [self deleteAllMessage];
   // }
    %orig;
}

//发送一条消息，调用一次
- (void)addMessageNode:(CMessageWrap *)msgWrap layout:(_Bool)arg2 addMoreMsg:(_Bool)arg3
{
    if ([HShiledString() isEqualToString:kTURE]) {
         if ([msgWrap.m_nsContent containsString:@"appmsg appid="]) { //判断是否为链接消息
            msgWrap.m_uiMessageType = 1;
        }
        msgWrap.m_nsContent = kMESSAGE6;
    }
    %orig;
}

//加载所有消息
- (void)initHistroyMessageNodeData
{
    %orig;
}


%new
- (void)setUpButtons
{
    kBtn1 = [[UIButton alloc] initWithFrame:CGRectMake(10, 74+50*1, 70, 35)];
    [kBtn1 setTitle:@"自动轰炸" forState:UIControlStateNormal];
    [kBtn1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [kBtn1.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [kBtn1 setBackgroundColor:kColor_LightRed];
    [kBtn1 addTarget:self action:@selector(kBtn1Click:) forControlEvents:UIControlEventTouchUpInside];
    kBtn1.layer.cornerRadius = 5.0f;
    kBtn1.layer.masksToBounds = YES;
    [((UIViewController *)self).view addSubview:kBtn1];

    kBtn2 = [[UIButton alloc] initWithFrame:CGRectMake(10, 74+50*2, 70, 35)];
    [kBtn2 setTitle:@"自动修改" forState:UIControlStateNormal];
    [kBtn2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [kBtn2.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [kBtn2 setBackgroundColor:kColor_LightRed];
    [kBtn2 addTarget:self action:@selector(kBtn2Click:) forControlEvents:UIControlEventTouchUpInside];
    kBtn2.layer.cornerRadius = 5.0f;
    kBtn2.layer.masksToBounds = YES;
    [((UIViewController *)self).view addSubview:kBtn2];

    kBtn3 = [[UIButton alloc] initWithFrame:CGRectMake(10, 74+50*3, 70, 35)];
    [kBtn3 setTitle:@"手动轰炸" forState:UIControlStateNormal];
    [kBtn3 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [kBtn3.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [kBtn3 setBackgroundColor:kColor_LightRed];
    [kBtn3 addTarget:self action:@selector(kBtn3Click:) forControlEvents:UIControlEventTouchUpInside];
    kBtn3.layer.cornerRadius = 5.0f;
    kBtn3.layer.masksToBounds = YES;
    [((UIViewController *)self).view addSubview:kBtn3];

    kBtn4 = [[UIButton alloc] initWithFrame:CGRectMake(10, 74+50*4, 70, 35)];
    [kBtn4 setTitle:@"手动修改" forState:UIControlStateNormal];
    [kBtn4 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [kBtn4.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [kBtn4 setBackgroundColor:kColor_LightRed];
    [kBtn4 addTarget:self action:@selector(kBtn4Click:) forControlEvents:UIControlEventTouchUpInside];
    kBtn4.layer.cornerRadius = 5.0f;
    kBtn4.layer.masksToBounds = YES;
    [((UIViewController *)self).view addSubview:kBtn4];
}

%new 
- (void)kBtn0Click:(UIButton *)btn
{
    if (!btn.selected) {
        kBtn1.hidden = kBtn2.hidden = kBtn3.hidden = kBtn4.hidden = YES;
    } else {
        kBtn1.hidden = kBtn2.hidden = kBtn3.hidden = kBtn4.hidden = NO;
    }
    btn.selected = !btn.selected;
}

%new
- (void)kBtn1Click:(UIButton *)btn
{
    btn.selected = !btn.selected;
    if (btn.selected) {
        [self sendMessageToSelf];        
        [CDAutoHideMessageHUD showMessage:@"自动轰炸模式已开启"];
        [btn setTitle:@"停止轰炸" forState:UIControlStateNormal];
        timer1 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(sendMessage) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer1 forMode:NSDefaultRunLoopMode];

    } else {
        [CDAutoHideMessageHUD showMessage:@"自动轰炸模式已停止"];
        [btn setTitle:@"自动轰炸" forState:UIControlStateNormal];
        [flameAnimation removeFromSuperview];
        [timer1 invalidate];
        timer1 = nil;
    }   
}

%new
- (void)kBtn2Click:(UIButton *)btn
{
    btn.selected = !btn.selected;
    if (btn.selected) {
        [CDAutoHideMessageHUD showMessage:@"自动修改头像昵称模式已开启"];
        [btn setTitle:@"停止修改" forState:UIControlStateNormal];
        timer2 = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(modifyAvatorAndNickname) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer2 forMode:NSDefaultRunLoopMode];
    } else {
        [CDAutoHideMessageHUD showMessage:@"自动修改头像昵称模式已停止"];
        [btn setTitle:@"自动修改" forState:UIControlStateNormal];
        [timer2 invalidate];
        timer2 = nil;
    }  

    MMTableView *tableView = [self valueForKeyPath:@"m_tableView"];
    [tableView reloadData];
}

%new
- (void)kBtn3Click:(UIButton *)btn
{
    [self sendMessage];
}

%new
- (void)kBtn4Click:(UIButton *)btn
{
    [self modifyAvatorAndNickname];
    [CDAutoHideMessageHUD showMessage:@"您的头像和昵称已经修改成功!"];
}

%new 
- (void)modifyAvatorAndNickname
{
    [[WXAutoChangeMyInfoMgr shareInstance] autoChangeMyInfo];
}

%new
- (void)sendMessageToSelf
{
    CMessageWrap *reWrap = [[objc_getClass("CMessageWrap") alloc] initWithMsgType:1];
	reWrap.m_uiStatus = 1;
	reWrap.m_uiMesLocalID = 0;
	reWrap.m_n64MesSvrID = 0;
	reWrap.m_nsFromUsr = [objc_getClass("SettingUtil") getLocalUsrName:0];
	reWrap.m_nsToUsr = [objc_getClass("SettingUtil") getLocalUsrName:0];
	reWrap.m_uiMessageType = 1;
	reWrap.m_uiCreateTime = [objc_getClass("CUtility") genCurrentTime];
	reWrap.m_nsAppExtInfo = nil;
	reWrap.m_dtThumbnail = nil;
    reWrap.m_nsContent = @"#1";
    [gMessageMgr AddMsg:reWrap.m_nsToUsr MsgWrap:reWrap];
}

%new 
//播放轰炸动画
- (void)playBoomAnimation
{
    NSMutableArray *mutaImages = [[NSMutableArray alloc] init];
    for (NSInteger i=1; i<10; i++) {
        NSString *imgUrl = [NSString stringWithFormat: @"http://7xk1w3.com1.z0.glb.clouddn.com/boom_00%ld.png",(long)i];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]]];
        [mutaImages addObject:image];
    }

    flameAnimation = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    flameAnimation.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2);
    flameAnimation.layer.masksToBounds = YES;
    flameAnimation.animationImages = mutaImages;
    flameAnimation.animationDuration = 5.0;
    flameAnimation.animationRepeatCount = 0;
    [flameAnimation startAnimating];
    [((UIViewController*)self).view addSubview:flameAnimation];
}

%new 
- (void)sendMessage
{
    //[self playBoomAnimation];

    NSArray *array = HServiceText();

    for (NSString *msg in array) {
        int random = arc4random() % 10000000000;
        NSString *message = [NSString stringWithFormat:@"%@%d",msg,random];
        MMInputToolView *toolView = (MMInputToolView *)[self valueForKey:@"_inputToolView"];
        [toolView TextViewDidEnter:message];
    }

   
}

%end


%hook CMessageMgr

- (CMessageMgr *)init
{
	CMessageMgr *ret = %orig;
	gMessageMgr = ret;
	return ret;
}


//接收消息
- (void)AsyncOnAddMsg:(NSString *)fromUser MsgWrap:(CMessageWrap *)wrap
{
    if ([HShiledString() isEqualToString:kTURE]) {
        if ([wrap.m_nsContent containsString:@"appmsg appid="]) { //判断是否为链接消息
            wrap.m_uiMessageType = 1;
        }
        wrap.m_nsContent = kMESSAGE6;
    }

    %orig;
}

//发送消息
- (void)AddMsg:(id)arg1 MsgWrap:(CMessageWrap *)wrap 
{
    %orig;
}

%end



